package subject

import (
	"oberserver/src/itf"
)



//被观察者
//被观察者的属性：观察者的存储等
type ConcreteSubject struct {
	observers map[string][]itf.Observer
}

//订阅消息
func (cs *ConcreteSubject) Regist(topic string, ob itf.Observer) {
	cs.observers[topic] = append(cs.observers[topic], ob)
}

//取消订阅
func (cs *ConcreteSubject) Deregist(topic string, ob itf.Observer) {

	temp := cs.observers[topic]
	length := len(temp)

	if length == 0 || temp == nil{
		delete(cs.observers, topic)
	}

	for k,v := range temp{
		if v == ob{
			temp[k] = temp[length-1]
			cs.observers[topic] = temp[0 : length-1]
		}
	}
}

//将更新后的状态通知每一个订阅者
func (cs *ConcreteSubject) Notify(e *itf.Event) {

	for _,v := range cs.observers[e.Topic] {
		//ob.Update(e)
		v.Update(e)
	}
}